import React, { useState, useEffect } from 'react';
import { Uploader } from 'react-vant';
import { Form, Input, message, Space, Button, Typography, Spin } from 'antd';
import axios from 'axios';
import styles from './UserProfile.module.css';


const { Title } = Typography;

const UserProfile = () => {
  const [form] = Form.useForm();
  const [userData, setUserData] = useState({});
  const [loading, setLoading] = useState(true);
  const [avatarLoading, setAvatarLoading] = useState(false);
  const [avatarUrl, setAvatarUrl] = useState(''); // 新增：单独管理头像URL
  const _id = sessionStorage.getItem('userid');

  // 获取用户数据
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await axios.get(`http://localhost:3000/getData`, { 
          params: { _id } 
        });
        
        if (response.data.data && response.data.data.length > 0) {
          const data = response.data.data[0];
          setUserData(data);
          setAvatarUrl(data.head || ''); // 初始化头像URL
          form.setFieldsValue({
            name: data.name,
            telp: data.telp,
          });
        } else {
          message.warning('未找到用户数据');
        }
      } catch (error) {
        message.error('获取用户信息失败');
        console.error('数据获取失败:', error);
      } finally {
        setLoading(false);
      }
    };

    fetchData();
  }, [_id, form]);

  // 处理表单提交（包含头像地址）
  const onFinish = async (values) => {
    // 合并头像URL到提交数据中
    const formData = {
      ...values,
      head: avatarUrl // 提交头像地址到后端
    };

    try {
      setLoading(true);
      const response = await axios.post(`http://localhost:3000/update`, { 
        _id, 
        ...formData 
      });
      
      if (response.data.code === 200) {
        message.success('信息修改成功');
        setUserData(prev => ({ 
          ...prev, 
          ...formData // 更新用户数据（包含头像）
        }));
      } else {
        message.error(response.data.message || '修改失败');
      }
    } catch (error) {
      message.error('网络请求失败，请重试');
      console.error('数据更新失败:', error);
    } finally {
      setLoading(false);
    }
  };

  // 头像上传处理
  const handleAvatarUpload = async (file) => {
    console.log('开始上传头像:', file);
    setAvatarLoading(true);
    
    try {
      const formData = new FormData();
      formData.append('file', file);
      
      const response = await axios.post(`http://localhost:3000/sc`, formData, {
        timeout: 10000
      });

      if (response.data.code === 200) {
        const newAvatarUrl = response.data.path;
        setAvatarUrl(newAvatarUrl); // 更新头像URL状态
        message.success('头像上传成功');
        return { url: newAvatarUrl, status: 'done' };
      } else {
        message.error(`上传失败: ${response.data.message || '未知错误'}`);
        return { status: 'error' };
      }
    } catch (error) {
      console.error('头像上传错误:', error);
      message.error('头像上传失败，请重试');
      return { status: 'error' };
    } finally {
      setAvatarLoading(false);
    }
  };

  // 限制只显示一个头像并处理上传
  const handleAfterRead = (files, detail) => {
    const file = files[0];
    if (file) {
      handleAvatarUpload(file.file).then(result => {
        detail.update([result]); // 更新Uploader显示的文件列表
      });
    }
  };

  return (
    <div className={styles.wrapper}>
      {loading ? (
        <Spin size="large" className={styles.loading} />
      ) : (
        <Form
          form={form}
          name="user_info"
          onFinish={onFinish}
          layout="vertical"
          className={styles.form}
        >
          <Title level={3} className={styles.title}>个人信息管理</Title>
          
          <div className={styles.avatarSection}>
            <Title level={4}>头像管理</Title>
            <Uploader
              accept="image/*"
              maxCount={1} // 限制最多上传1张图片
              afterRead={handleAfterRead}
              previewSize={120}
              className={styles.avatarUploader}
              fileList={avatarUrl ? [{ url: avatarUrl, status: 'done' }] : []} // 使用独立状态控制显示
              showUpload={!avatarLoading} // 上传中时隐藏上传按钮
            />
            {avatarLoading && <Spin size="small" className={styles.uploadSpinner} />}
          </div>

          <Form.Item
            label="用户名"
            name="name"
            rules={[{ required: true, message: '请填写用户名' }]}
          >
            <Input placeholder="请输入用户名" />
          </Form.Item>

          <Form.Item
            label="手机号"
            name="telp"
            rules={[
              { required: true, message: '请填写手机号' },
              { pattern: /^1[3-9]\d{9}$/, message: '请输入正确手机号格式' }
            ]}
          >
            <Input placeholder="请输入手机号" />
          </Form.Item>

          <Form.Item wrapperCol={{ offset: 0, span: 24 }}>
            <Space>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                className={styles.saveButton}
              >
                保存修改
              </Button>
              <Button 
                type="default"
                onClick={() => form.resetFields()}
                className={styles.resetButton}
              >
                重置表单
              </Button>
            </Space>
          </Form.Item>
        </Form>
      )}
    </div>
  );
};

export default UserProfile;